import React, { useState, useEffect } from "react";
import { Button, Table, Tooltip, Input, Badge, Layout, Menu } from "antd";
import { PicLeftOutlined } from "@ant-design/icons";
import { getUserTodoTask } from "../../api/workbench";
import styles from "../../styles/pages/workbenches.module.css";

const { Sider, Content } = Layout;
const { Search } = Input;

const Workbenches = () => {
  const [loading, setLoading] = useState(false);
  const [currentTab, setCurrentTab] = useState("todo");
  const [searchValue, setSearchValue] = useState("");

  // 菜单项配置
  const menuItems = [
    {
      key: "todo",
      label: "全部待办",
      count: 8,
      children: [
        { key: "order", label: "订单", count: 2 },
        { key: "travel", label: "差旅", count: 1 },
        { key: "seal", label: "公章", count: 0 },
        { key: "contract", label: "合同/文件", count: 3 },
        { key: "quotation", label: "报价单", count: 1 },
        { key: "finance", label: "财务管理", count: 4 },
        { key: "special", label: "专项付款", count: 0 },
        { key: "asset", label: "资产管理", count: 2 },
        { key: "purchase", label: "采购管理", count: 1 },
        { key: "product", label: "产品/项目/市场", count: 3 },
        { key: "sample", label: "预收样", count: 0 },
        { key: "other", label: "其他", count: 1 },
        { key: "task", label: "任务分配", count: 2 }
      ]
    },
    { key: "done", label: "已办", count: 3 },
    { key: "cc", label: "抄送", count: 2 },
    { key: "transfer", label: "转办", count: 1 },
    { key: "reject", label: "拒绝", count: 0 },
    { key: "sign", label: "加签", count: 4 },
    { key: "search", label: "检索", count: 0 },
    { key: "suspend", label: "挂起", count: 2 },
    { key: "delegate", label: "委托", count: 1 },
    { key: "initiated", label: "我发起的", count: 5 }
  ];

  // 分页配置
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条`,
    position: ['bottomLeft'],
    size: 'small'
  });

  const [tableData, setTableData] = useState([]);

  // 获取表格数据
  const fetchData = async (current = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const res = await getUserTodoTask({
        pageNum: current,
        pageSize: pageSize,
        flowTitle: searchValue,
        belongSystem: "亿康CRM",
        flowDescribe: "",
        taskName: "",
        recordType: "",
        processOwnerName: "",
        processOwnerDeptName: "",
        processInstanceId: "",
      });
      setTableData(res.rows || []);
      setPagination((prev) => ({
        ...prev,
        total: res.total,
      }));
    } catch (error) {
      console.error("获取数据失败：", error);
    } finally {
      setLoading(false);
    }
  };

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination((prev) => ({
      ...prev,
      current: pagination.current,
      pageSize: pagination.pageSize,
    }));
    fetchData(pagination.current, pagination.pageSize);
  };

  // 处理搜索
  const onSearch = (value) => {
    setSearchValue(value);
    setPagination((prev) => ({ ...prev, current: 1 }));
    fetchData(1, pagination.pageSize);
  };

  // 处理菜单点击
  const handleMenuClick = ({ key }) => {
    setCurrentTab(key);
    fetchData(1, pagination.pageSize);
  };

  // 添加回 handleModel 方法
  const handleModel = (record) => {
    window.$wujie?.bus.$emit("handleModel", record);
  };

  // 添加回 showRightDrawer 方法
  const showRightDrawer = (row) => {
    window.$wujie?.bus.$emit("showRightDrawer", row);
  };

  // 添加回 handlePending 方法
  const handlePending = async (record) => {
    // 处理挂起逻辑
  };

  useEffect(() => {
    fetchData();
  }, []);

  const columns = [
    {
      title: "到达时间",
      dataIndex: "taskStartTime",
      key: "taskStartTime",
      ellipsis: true,
    },
    {
      title: "流程标题",
      dataIndex: "processDefinitionName",
      key: "processDefinitionName",
      ellipsis: true,
    },
    {
      title: "流程标识",
      dataIndex: "processInstanceId",
      width: 100,
      key: "processInstanceId",
      render: (text, record) => (
        <a onClick={() => showRightDrawer(record)}>{text}</a>
      ),
    },
    {
      title: "流程描述",
      dataIndex: "flowDescribe",
      key: "flowDescribe",
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: "当前节点",
      dataIndex: "taskName",
      key: "taskName",
    },
    {
      title: "流程动态",
      dataIndex: "isPending",
      key: "isPending",
      width: 90,
      render: (_, record) => (
        <PicLeftOutlined
          style={{ color: "#1890ff", fontSize: "16px", cursor: "pointer" }}
          onClick={() => handleModel(record)}
        />
      ),
    },
    {
      title: "申请人",
      dataIndex: "processOwnerName",
      key: "processOwnerName",
      width: 90,
    },
    {
      title: "申请人部门",
      dataIndex: "processOwnerDeptName",
      key: "processOwnerDeptName",
      width: 120,
      ellipsis: true,
    },
    {
      title: "是否挂起",
      width: 90,
      align: "center",
      render: (_, record) => (
        <Button
          type="primary"
          size="small"
          onClick={() => handlePending(record)}
        >
          挂起
        </Button>
      ),
    },
  ];

  return (
    <Layout className={styles.workbenchLayout}>
      <Sider className={styles.sider}>
        <Menu
          mode="inline"
          selectedKeys={[currentTab]}
          defaultOpenKeys={['todo']}
          onClick={handleMenuClick}
          items={menuItems.map((item) => ({
            key: item.key,
            label: (
              <div className={styles.menuItem}>
                <span>{item.label}</span>
                <Badge count={item.count} showZero={false} size="small" />
              </div>
            ),
            children: item.children?.map(child => ({
              key: child.key,
              label: (
                <div className={styles.menuItem}>
                  <span>{child.label}</span>
                  <Badge count={child.count} showZero={false} size="small" />
                </div>
              )
            }))
          }))}
        />
      </Sider>
      <Content className={styles.content}>
        <Search
          placeholder="请输入关键词搜索"
          onSearch={onSearch}
          enterButton="搜索"
          size="middle"
          style={{ width: 320, marginBottom: "10px" }}
        />
        <Table
          loading={loading}
          columns={columns}
          dataSource={tableData}
          bordered={true}
          size="small"
          pagination={pagination}
          onChange={handleTableChange}
          rowClassName={(record, index) =>
            index % 2 === 1 ? styles["table-striped"] : ""
          }
        />
      </Content>
    </Layout>
  );
};

export default Workbenches;
